//
//  WaterFallLayout.swift
//  HHSwift
//
//  Created by 华宏 on 2020/1/29.
//  Copyright © 2020 huahong. All rights reserved.
//

import UIKit

@objc protocol WaterFallLayoutDelegate {
    
    func waterFallLayout(layout:WaterFallLayout,heightFor indexPath:IndexPath,itemWidth:CGFloat) -> CGFloat
}

class WaterFallLayout: UICollectionViewFlowLayout {

    /// 列数，默认2
  @objc  var columnCount = 2
    
  @objc var delegate:WaterFallLayoutDelegate?
    
  fileprivate  var attrsArray:[UICollectionViewLayoutAttributes] = []
  fileprivate  var columnHeights:[CGFloat] = []
  fileprivate  var contentHeight:CGFloat = 0.0
    
    override func prepare() {
        super.prepare()
        
        self.contentHeight = 0
        self.attrsArray.removeAll()
        self.columnHeights.removeAll()
        
        for _ in 0..<columnCount {
            columnHeights.append(self.sectionInset.top)
        }
        
        guard let count:Int = self.collectionView?.numberOfItems(inSection: 0) else { return }
        for i in 0..<count {
            let indexPath = IndexPath(item: i, section: 0)
            guard let attrs = self.layoutAttributesForItem(at: indexPath) else { return }
            attrsArray.append(attrs)
            
        }
        
        
    }
   
    
    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        
        let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
        guard let collectionWidth = self.collectionView?.bounds.size.width else { return attributes }
        let width = (collectionWidth - self.sectionInset.left - self.sectionInset.right - (CGFloat(columnCount) - 1) * self.minimumInteritemSpacing) / CGFloat(columnCount)
        let height = self.delegate?.waterFallLayout(layout: self, heightFor: indexPath, itemWidth: width)
        
        //找出来最短后 就把下一个cell 添加到底下
        var index = 0
        var minColumnHeight = columnHeights.first ?? 0
        
        for i in 0..<columnCount {
            
            // 取得第i列的高度
            let columnHeight = columnHeights[i]
            
            //找出最高的高度
            contentHeight = max(contentHeight, columnHeight)
            
            // 找出最短的那一列
            index = (Float(minColumnHeight) <= Float(columnHeight)) ? index : i
            minColumnHeight = min(minColumnHeight, columnHeight)
        }
        
        let x = self.sectionInset.left + CGFloat(index) * (width + self.minimumInteritemSpacing)
        var y = minColumnHeight
        if y != self.sectionInset.top {
            y += self.minimumLineSpacing
        }
        
        attributes.frame = CGRect(x: x, y: y, width: width, height: height ?? 0)
        
        // 更新最短那列的高度
        columnHeights[index] = attributes.frame.maxY
        
        return attributes
        
    }
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]?
    {
        return attrsArray
    }
    
    override var collectionViewContentSize: CGSize
    {
        return CGSize(width: 0, height: self.contentHeight + self.sectionInset.bottom)
    }
}
